const path = require ('path');
const fs = require('fs');

const ini = require('node-ini');
ini.encoding = 'utf-8';

/**
 * 兼容老版本的配置文件
 * 不再使用node=ini，换用新写的Ini文件
 */
function refreshIni() {
    let dataDir = "";
    let iniConfig = "";
    if (process.env.NODE_ENV === 'production') {
        dataDir = path.dirname(process.execPath) + '/resources/data/';
        iniConfig = dataDir + "config.ini";
    } else {
        dataDir = './data/';
        iniConfig = dataDir + "config_test.ini";
    }
    if(fs.existsSync(dataDir + "old.cfg")){
        let INI = require("../../static/utils/IniOperation");
        let newIni = INI.loadFileSync(iniConfig);
        let oldIni = INI.loadFileSync(dataDir + "old.cfg");

        let oldDataDir = oldIni.getOrCreateSection("data");
        let newDataDir = newIni.getOrCreateSection("data");
        newDataDir["dataDir"] = oldDataDir["dataDir"];
        fs.unlinkSync(iniConfig);
        fs.writeFileSync(iniConfig, newIni);
        fs.unlinkSync(dataDir + "old.cfg");
    }
}

refreshIni();

function readIniFile(section, key) {
    let config = null;
    if (process.env.NODE_ENV === 'production') {
        config = ini.parseSync(path.dirname(process.execPath) + '/resources/data/config.ini');
    } else {
        config = ini.parseSync('./data/config_test.ini');
    }
    if (config[section]) {
        return config[section][key] ? config[section][key] : '';
    } else {
        return '';
    }
}

module.exports = readIniFile;
